package yhao.infra.web.interceptor.logger.support;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import yhao.infra.common.util.CommonDateUtil;
import yhao.infra.web.common.util.CommonWebUtil;
import yhao.infra.web.interceptor.logger.context.RequestContext;

import jakarta.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Date;

import static yhao.infra.common.logger.CommonLoggerFactory.getValue;
import static yhao.infra.common.logger.CommonLoggerFactory.replaceUnNeed;

/**
 * @author yoara
 * <p> Created on 2021/4/23 </p>
 */
public class StatServiceLoggerBuilder implements LoggerBuilder {
    @Override
    public String doLog(HttpServletRequest request, RequestContext digestContext) throws Exception {
        String errMsg = digestContext.getErrMsg();
        boolean success = StringUtils.isEmpty(errMsg);
        boolean needParam = digestContext.getForm()!=null;

        long startTime = digestContext.getTimeKey();
        long endTime = System.currentTimeMillis();

        String id = getValue(digestContext.getRequestId());
        String visitTime = getValueDate(new Date(startTime));
        String appName = getValue(digestContext.getAppName());

        String times = getValue(endTime - startTime);
        String url = getValue(CommonWebUtil.getHostContext(request));
        String uri = replaceUnNeed(request.getRequestURI());

        String _errMsg    = getValue(errMsg);
        String _success   = getValue(success);
        String ip        = getValue(String.join(",",CommonWebUtil.getIpAddr(request)));
        String host      = getValue(InetAddress.getLocalHost().getHostAddress());

        JSONObject result = new JSONObject();

        result.put("id",id);
        result.put("visitTime",visitTime);
        result.put("appName",appName);

        result.put("usetime",times);
        result.put("url",url);
        result.put("uri",uri);

        if(needParam){
            String form = getValue(JSONObject.toJSONString(digestContext.getForm()));
            String formClass = getValue(digestContext.getForm().getClass().getName());

            result.put("params",form);
            result.put("formClass",formClass);
        }
        result.put("errMsg",_errMsg);
        result.put("success",_success);
        result.put("clientIp",ip);
        result.put("host",host);

        return result.toJSONString();
    }

    public static String getValueDate(Date value) {
        return value == null ? "-" :
                CommonDateUtil.formatDateToString(value,"yyyy-MM-dd HH:mm:ss SSS");
    }
}
